<template>
  <el-dialog v-model="visible" title="联系人审核" width="600px" :before-close="handleClose">
    <div v-loading="loading" class="contact-review">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="审核类型">
          <el-tag>{{ getTypeLabel(reviewDetail?.review_type) }}</el-tag>
        </el-form-item>

        <el-form-item label="联系人">
          {{ reviewDetail?.contact_name }}
        </el-form-item>

        <el-form-item label="客户">
          {{ reviewDetail?.customer_name }}
        </el-form-item>

        <el-form-item label="申请人">
          {{ reviewDetail?.user_name }}
        </el-form-item>

        <el-form-item label="申请时间">
          {{ reviewDetail?.create_time }}
        </el-form-item>

        <el-form-item label="审核结果" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="2">通过</el-radio>
            <el-radio :label="3">驳回</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="审核意见" prop="review_comment">
          <el-input
            v-model="form.review_comment"
            type="textarea"
            :rows="3"
            placeholder="请输入审核意见"
          />
        </el-form-item>
      </el-form>

      <!-- 显示修改前后的对比 -->
      <div v-if="reviewDetail?.review_type === 2" class="diff-section">
        <h4>修改内容对比</h4>
        <el-descriptions :column="2" border>
          <el-descriptions-item v-for="field in diffFields" :key="field.key" :label="field.label">
            <div class="diff-item">
              <div class="original">
                <span class="label">原值：</span>
                {{ getFieldValue(reviewDetail?.original_data, field.key) }}
              </div>
              <div class="new">
                <span class="label">新值：</span>
                {{ getFieldValue(reviewDetail?.new_data, field.key) }}
              </div>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </div>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import { reviewApi } from '@/api/crm'

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    reviewId: {
      type: Number,
      default: 0,
    },
  })

  const emit = defineEmits(['update:modelValue', 'success'])

  const visible = computed({
    get: () => props.modelValue,
    set: value => emit('update:modelValue', value),
  })

  const formRef = ref()
  const loading = ref(false)
  const submitting = ref(false)

  const form = reactive({
    status: 2,
    review_comment: '',
  } as Record<string, any>)

  const rules = {
    status: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
    review_comment: [{ required: true, message: '请输入审核意见', trigger: 'blur' }],
  }

  const reviewDetail = ref<any>(null)

  const typeOptions = ref<Array<{ value: number; label: string }>>([])

  // 对比字段配置
  const diffFields = [
    { key: 'name', label: '姓名' },
    { key: 'position', label: '职务' },
    { key: 'phone', label: '电话' },
    { key: 'wechat', label: '微信' },
    { key: 'email', label: '邮箱' },
    { key: 'is_primary', label: '主要联系人' },
  ]

  // 获取审核详情
  const getReviewDetail = async () => {
    if (!props.reviewId) return

    loading.value = true
    try {
      // 这里需要根据实际情况调整API调用
      // const res = await reviewApi.detail({ id: props.reviewId })
      // reviewDetail.value = res.data

      // 模拟数据
      reviewDetail.value = {
        review_type: 2,
        contact_name: '张三',
        customer_name: '测试公司',
        user_name: '申请人',
        create_time: '2024-01-01 10:00:00',
        original_data:
          '{"name":"张三","position":"经理","phone":"13800138000","wechat":"zhangsan","email":"zhangsan@test.com","is_primary":0}',
        new_data:
          '{"name":"张三","position":"总监","phone":"13800138000","wechat":"zhangsan_new","email":"zhangsan@test.com","is_primary":1}',
      }
    } catch (error) {
      console.error('获取审核详情失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 获取选项数据
  const getOptions = async () => {
    try {
      // 使用默认选项数据
      typeOptions.value = [
        { value: 1, label: '新增联系人' },
        { value: 2, label: '修改联系人' },
        { value: 3, label: '删除联系人' },
      ]
    } catch (error) {
      console.error('获取选项失败:', error)
    }
  }

  // 获取类型标签
  const getTypeLabel = (value: number) => {
    const option = typeOptions.value.find(item => item.value === value)
    return option ? option.label : '-'
  }

  // 获取字段值
  const getFieldValue = (data: string, field: string) => {
    if (!data) return '-'
    try {
      const obj = JSON.parse(data)
      const value = obj[field]

      if (field === 'is_primary') {
        return value ? '是' : '否'
      }

      return value || '-'
    } catch (error) {
      return '-'
    }
  }

  // 提交表单
  const handleSubmit = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()

      submitting.value = true

      const submitData = {
        ...form,
        id: props.reviewId,
      }

      await reviewApi.update(props.reviewId, submitData)
      ElMessage.success('审核成功')

      emit('success')
      handleClose()
    } catch (error) {
      console.error('提交失败:', error)
    } finally {
      submitting.value = false
    }
  }

  // 关闭对话框
  const handleClose = () => {
    // 重置表单
    if (formRef.value) {
      formRef.value.resetFields()
    }
    Object.keys(form).forEach(key => {
      if (key !== 'status') {
        form[key] = ''
      }
    })
    form.status = 2
    reviewDetail.value = null

    visible.value = false
  }

  // 监听对话框显示状态
  watch(visible, newVal => {
    if (newVal && props.reviewId) {
      getReviewDetail()
      getOptions()
    }
  })
</script>

<style scoped>
  .contact-review {
    max-height: 70vh;
    overflow-y: auto;
  }

  .diff-section {
    margin-top: 20px;
    padding: 15px;
    background: #f5f7fa;
    border-radius: 4px;
  }

  .diff-item {
    font-size: 12px;
  }

  .diff-item .label {
    color: #909399;
    font-weight: bold;
  }

  .diff-item .original {
    color: #f56c6c;
    margin-bottom: 4px;
  }

  .diff-item .new {
    color: #67c23a;
  }
</style>
